const express = require('express');
let router = express.Router();
const pool = require('../pool');

/*** 按发布时间逆序返回新闻列表 ***/
router.get('/list/:pageNum', (req, res) => {
    // 读取请求数据
    let pageNum = req.params.pageNum;

    // 分页器对象
    let pager = {
        totalRecord: 0, // 总记录数
        pageSize: 5, // 每页显示条数
        pageCount: 0, // 总页数
        pageNum: parseInt(pageNum),
        data: []
    };
    pool.query('SELECT count(*) AS c FROM mf_news', (err, result) => {
        if (err) throw err;
        console.log(result[0].c);
        pager.totalRecord = result[0].c;
        pager.pageCount = Math.ceil(pager.totalRecord/pager.pageSize);

        pool.query('select * from mf_news order by pubTime DESC limit ?,?', [(pager.pageNum-1)*pager.pageSize, pager.pageSize], (err, result) => {
            if (err) throw err;
            pager.data = result;
            res.json(pager);
        })
    });

    // 输出响应信息
    // let pager = {pageNum: n};
});

/**
 * 根据新闻ID返回新闻详情
 */
router.get('/:nid', (req, res) => {
    let nid = req.params.nid;

    pool.query('SELECT * FROM mf_news WHERE nid=?', [nid], (err, result) => {
        if (err) throw err;
        res.json(result);
    });
    // res.json({nid, title: "title" + nid});
});

module.exports = router;